package pers.lls.im.core.bootstrap.handler.base;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lihuan
 * @version V1.0 创建时间：2019/8/02
 * Copyright 2019 by landray & STIC
 */
@Slf4j
public abstract class AbstractHandler extends SimpleChannelInboundHandler<Object> {


    Handler handler;

    public AbstractHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            dealTwsfMessage(ctx, (TextWebSocketFrame) msg);
        } else if (msg instanceof WebSocketFrame) {
            dealWsfMessage(ctx, (WebSocketFrame) msg);
        } else if (msg instanceof FullHttpRequest) {
            dealFhrMessage(ctx, (FullHttpRequest) msg);
        }
    }

    /**
     * 二进制消息
     * @param ctx
     * @param msg
     */
    protected abstract void dealWsfMessage(ChannelHandlerContext ctx, WebSocketFrame msg);

    /**
     * 文档消息
     * @param ctx
     * @param msg
     */
    protected abstract void dealTwsfMessage(ChannelHandlerContext ctx, TextWebSocketFrame msg);

    /**
     * @param ctx
     * @param msg
     */
    protected abstract void dealFhrMessage(ChannelHandlerContext ctx, FullHttpRequest msg);

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            handler.close(ctx.channel());
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

}
